const catModel = require('../db/cat')
const xy = require('../utils/xy')
const writeErr = require('../utils/writeErr')

module.exports = {
    // 处理获取所有分类
    async getall(req, resp) {
        try{
            let docs = await catModel.find()
            xy(resp, 200, '分类获取成功！', {
                cats: docs
            })
        }catch(err) {
            writeErr(err)
            // 查询失败
            xy(resp, 504, '分类获取失败！')
        }
    },
    // 后台
    async list(req, resp) {
        try{
            let catlist = await catModel.find()
            xy(resp, 200, '分类获取成功！', {
                catlist: catlist.reverse()
            })
        } catch(err) {
            writeErr(err)
            xy(resp, 530, '分类获取失败！')
        }
    },
    async add(req, resp) {
        let {catname} = req.body
        if(!catname) {
            xy(resp, 401, '缺少参数！')
            return
        }
        try{
            await catModel.insertMany({catname})
            xy(resp, 200, '分类添加成功！')
        } catch(err) {
            writeErr(err)
            xy(resp, 531, '分类添加失败！')
        }
    },
    async edit(req, resp) {
        let {id} = req.params
        let {catname} = req.body
        if(!catname) {
            xy(resp, 401, '缺少参数！')
            return
        }
        try{
            await catModel.updateOne({_id: id}, {catname})
            xy(resp, 200, '分类修改成功！')
        } catch(err) {
            writeErr(err)
            xy(resp, 532, '分类修改失败！')
        }
    },
    async del(req, resp) {
        let {id} = req.params
        try{
            await catModel.deleteOne({_id: id})
            xy(resp, 200, '分类删除成功！')
        } catch(err) {
            writeErr(err)
            xy(resp, 533, '分类删除失败！')
        }
    }
}